package com.rc.saas.tenant.service.msg;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.mapper.msg.TenantCustomMsgMapper;
import com.rc.saas.tenant.model.msg.TenantCustomMsg;
import com.rc.saas.tenant.model.msg.TenantCustomMsgExample;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.tenant.TenantCustomMsgSearch;
import com.rc.saas.tenant.vo.msg.TenantCustomMsgResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * @author frog
 * @date 2019/12/17
 */
@Service
public class TenantCustomMsgServiceImpl implements TenantCustomMsgService {

    @Autowired
    private TenantCustomMsgMapper tenantCustomMsgMapper;

    @Override
    public TenantCustomMsgMapper getMapper() {
        return tenantCustomMsgMapper;
    }

    @Override
    public PageInfo<TenantCustomMsgResultVo> searchByCondition(TenantCustomMsgSearch tenantCustomMsgSearch) {
        PageHelper.startPage(tenantCustomMsgSearch.getOffset(), tenantCustomMsgSearch.getLimit());
        List<TenantCustomMsgResultVo> orderList = tenantCustomMsgMapper.searchByCondition(tenantCustomMsgSearch);
        return new PageInfo<TenantCustomMsgResultVo>(orderList);
    }

    @Override
    public void insertMessage(Long memberId, String content, TenantUser user) {

        Date date = new Date();
        TenantCustomMsg tenantCustomMsg = new TenantCustomMsg();
        tenantCustomMsg.setMemberId(memberId);
        tenantCustomMsg.setTenantUserId(user.getTenantUserId());
        tenantCustomMsg.setSendTime(date);
        //是否已读 0未读 1已读 默认0
        tenantCustomMsg.setIsRead("1");
        tenantCustomMsg.setMsgType("1");
        tenantCustomMsg.setContent(content);
        tenantCustomMsgMapper.insertSelective(tenantCustomMsg);

        //将所有未读消息设置回复人
        TenantCustomMsgExample example = new TenantCustomMsgExample();
        example.createCriteria().andMemberIdEqualTo(memberId).andTenantUserIdIsNull();
        List<TenantCustomMsg> tenantCustomMsgs = tenantCustomMsgMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(tenantCustomMsgs)) {
            for (TenantCustomMsg customMsg : tenantCustomMsgs) {
                customMsg.setTenantUserId(user.getTenantUserId());
                tenantCustomMsgMapper.updateByPrimaryKeySelective(customMsg);
            }
        }

    }

    @Override
    public long countUnreadMsg(String tenantCode) {
        TenantCustomMsgExample example = new TenantCustomMsgExample();
        example.createCriteria().andTenantCodeEqualTo(tenantCode).
                andMsgTypeEqualTo("0").andIsReadEqualTo("0");
        long count = tenantCustomMsgMapper.countByExample(example);
        return count;
    }
}
